﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ReporterEngine.Methods
{
    public class ClosestParent : BaseMethod
    {
        public override bool IsUseable(LexPath.PathToken token)
        {
            return token.Kind == LexPath.TokenKind.Method && !string.IsNullOrEmpty(token.PathExp) && token.PathExp.ToLower() == "closestparent";
        }

        public override sQuery Execute(LexPath.PathToken token, sQuery query)
        {
            var result = query.New();
            //
            var typeList = query.GetArgValuesForType(token.Args);

            foreach (var element in query.Elements)
            {
                var parent = query._model.GetXParent(element);

                while (parent != null && !result.Elements.Contains(parent))
                {
                    foreach (var typeName in typeList)
                    {
                        var parentType = query._model.GetTypeName(parent);
                        if(parentType.ToLower() == typeName.ToLower())
                        {
                            result.Elements.Add(parent);
                            break;
                        }
                    }

                    parent = query._model.GetXParent(parent);
                }
            }

            return result;
        }

        public override MethodDescription[] GetMethodNames()
        {
            return new MethodDescription[] { new MethodDescription { Name = "closestParent" } };
        }
    }
}
